#!/bin/bash
# 通用子模块镜像管理器 - 纯 Shell 版本

GIT_CMD="/c/Program Files/Git/bin/git.exe"

# 镜像源列表
MIRROR_SOURCES=(
    "https://gitee.com/mirrors"
    "https://gitee.com/uesoft" 
    "https://gitcode.com/mirrors"
)

show_help() {
    echo "通用子模块镜像管理器 (Shell 版本)"
    echo "自动发现、评估和配置最优镜像"
    echo ""
    echo "使用方法: $0 <command>"
    echo ""
    echo "命令:"
    echo "  setup   为所有子模块自动寻找并配置最优镜像"
    echo "  init    初始化子模块（使用配置的镜像）"
    echo "  check   检查当前镜像配置"
    echo "  test <url>  测试单个项目的镜像发现"
    echo "  help    显示此帮助信息"
}

extract_project_name() {
    local git_url="$1"
    # 移除 .git 后缀
    local clean_url="${git_url%.git}"
    # 提取最后一部分作为项目名
    echo "$clean_url" | sed 's|.*/||'
}

generate_mirror_urls() {
    local original_url="$1"
    local project_name="$2"
    
    local mirror_urls=()
    
    for source in "${MIRROR_SOURCES[@]}"; do
        mirror_urls+=("${source}/${project_name}")
        
        # 处理 lib 前缀变体
        if [[ "$project_name" == lib* ]]; then
            local alt_name="${project_name#lib}"
            mirror_urls+=("${source}/${alt_name}")
        elif [[ "$project_name" != *lib* ]]; then
            mirror_urls+=("${source}/lib${project_name}")
        fi
    done
    
    printf "%s\n" "${mirror_urls[@]}"
}

evaluate_mirror() {
    local mirror_url="$1"
    
    echo -n "   评估: $mirror_url ... "
    
    # 检查可用性
    if "$GIT_CMD" ls-remote "$mirror_url" >/dev/null 2>&1; then
        # 检查标签数量
        local tag_count=$("$GIT_CMD" ls-remote --tags "$mirror_url" 2>/dev/null | wc -l)
        
        if [ "$tag_count" -gt 10 ]; then
            echo "✅ 优秀 ($tag_count 标签)"
            return 90
        elif [ "$tag_count" -gt 5 ]; then
            echo "✅ 良好 ($tag_count 标签)" 
            return 70
        else
            echo "✅ 可用 ($tag_count 标签)"
            return 50
        fi
    else
        echo "❌ 不可用"
        return 0
    fi
}

find_best_mirror() {
    local original_url="$1"
    local project_name=$(extract_project_name "$original_url")
    
    echo "为 $project_name 寻找最优镜像..."
    
    local best_mirror=""
    local best_score=0
    
    while IFS= read -r mirror_url; do
        local score
        score=$(evaluate_mirror "$mirror_url")
        
        if [ "$score" -gt "$best_score" ]; then
            best_score=$score
            best_mirror="$mirror_url"
        fi
    done < <(generate_mirror_urls "$original_url" "$project_name")
    
    if [ -n "$best_mirror" ] && [ "$best_score" -ge 50 ]; then
        echo "✅ 找到最优镜像: $best_mirror (得分: $best_score)"
        echo "$best_mirror"
        return 0
    else
        echo "❌ 未找到合适镜像 (最佳得分: $best_score)"
        return 1
    fi
}

setup_mirror_for_submodule() {
    local submodule_path="$1"
    local original_url="$2"
    
    echo
    echo "处理子模块: $submodule_path"
    echo "原始 URL: $original_url"
    
    local best_mirror
    best_mirror=$(find_best_mirror "$original_url")
    
    if [ $? -eq 0 ] && [ -n "$best_mirror" ]; then
        # 配置镜像规则
        "$GIT_CMD" config --local "url.${best_mirror}.insteadOf" "$original_url"
        
        if [ $? -eq 0 ]; then
            echo "✅ 镜像配置成功: $original_url -> $best_mirror"
            return 0
        else
            echo "❌ 镜像配置失败"
            return 1
        fi
    else
        echo "❌ 无法为该子模块找到合适镜像"
        return 1
    fi
}

process_all_submodules() {
    echo "=== 开始处理所有子模块 ==="
    
    # 获取子模块信息
    local submodule_output
    submodule_output=$("$GIT_CMD" submodule status)
    
    if [ $? -ne 0 ]; then
        echo "❌ 无法获取子模块信息"
        return 1
    fi
    
    local success_count=0
    local total_count=0
    
    while IFS= read -r line; do
        if [ -z "$line" ]; then
            continue
        fi
        
        local parts=($line)
        local submodule_path="${parts[1]}"
        
        # 获取子模块 URL
        local original_url
        original_url=$("$GIT_CMD" config --file .gitmodules "submodule.${submodule_path}.url")
        
        if [ $? -eq 0 ]; then
            total_count=$((total_count + 1))
            
            if setup_mirror_for_submodule "$submodule_path" "$original_url"; then
                success_count=$((success_count + 1))
            fi
        else
            echo "❌ 无法获取子模块 $submodule_path 的 URL"
        fi
    done <<< "$submodule_output"
    
    echo
    echo "=== 处理完成 ==="
    echo "成功配置: $success_count/$total_count 个子模块"
    
    return $((success_count > 0 ? 0 : 1))
}

init_submodules() {
    echo "=== 初始化子模块 ==="
    "$GIT_CMD" submodule update --init --recursive
    
    if [ $? -eq 0 ]; then
        echo "✅ 子模块初始化完成"
        return 0
    else
        echo "❌ 子模块初始化失败"
        return 1
    fi
}

check_config() {
    echo "=== 检查镜像配置 ==="
    "$GIT_CMD" config --local --list | grep -i insteadof
}

test_mirror_discovery() {
    local test_url="$1"
    
    if [ -z "$test_url" ]; then
        echo "请提供要测试的 Git URL"
        echo "示例: $0 test https://github.com/libexpat/libexpat"
        return 1
    fi
    
    echo "=== 测试镜像发现: $test_url ==="
    find_best_mirror "$test_url"
}

# 主程序
case "${1:-help}" in
    "setup")
        process_all_submodules
        ;;
    "init")
        init_submodules
        ;;
    "check")
        check_config
        ;;
    "test")
        test_mirror_discovery "$2"
        ;;
    "help")
        show_help
        ;;
    *)
        echo "未知命令: $1"
        show_help
        exit 1
        ;;
esac
